import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:matuo/page/tool/BleConnectPage.dart';
import 'package:matuo/utils/DIYColors.dart';
import 'package:matuo/utils/Utils.dart';

import '../../ble/ScanBluetoothUtil.dart';
import '../../route/RouteUtils.dart';
import '../../utils/Logcat.dart';

class ScanDevicePage extends StatefulWidget {
  const ScanDevicePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ScanDevicePageState();
  }
}

class _ScanDevicePageState extends State<ScanDevicePage>
    with SingleTickerProviderStateMixin {
  late AnimationController _rotationController;
  bool _isVisible = false;

  final List<ScanResult> _scanResults = [];

  @override
  void initState() {
    super.initState();
    scan();
    animation();
  }

  @override
  void dispose() {
    super.dispose();
    ScanBluetoothUtil.instance.stopPressed();
  }

  void scan() {
    ScanBluetoothUtil.instance.scanPressed(
        scanResultCallback: (scanResult, pid) {
      Logcat.instance.d("PID = ${pid}");
      setState(() {
        _scanResults.add(scanResult);
      });
    }, scanningSubscriptionCallback: (state) {
      setState(() {
        if (!state) {
          _rotationController.stop();
        }
        _isVisible = !state;
      });
    });
  }

  void animation() {
    _rotationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        backgroundColor: DIYColors.gray_f4,
        appBar: Utils.instance.appBarLeft(context, "添加设备"),
        body: SafeArea(
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
          SizedBox(height: 20.h),
          Center(
              child: Container(
                  width: 165.w,
                  height: 165.h,
                  decoration:
                      Utils.instance.decorationImage("animation_iv_bg", 1.r),
                  child: RotationTransition(
                      turns: _rotationController,
                      child: Image.asset(
                        Utils.instance.getImagePathPNG("animation_iv"),
                        width: 165.w,
                        height: 165.h,
                      )))),
          SizedBox(height: 20.h),
          Text("正在扫描...",
              style: TextStyle(color: Colors.black, fontSize: 16.sp)),
          SizedBox(height: 10.h),
          Text("正在扫描可用设备",
              style: TextStyle(color: DIYColors.gray_99, fontSize: 14.sp)),
          SizedBox(height: 20.h),
          Visibility(
              visible: _isVisible,
              child: TextButton(
                  onPressed: () {
                    resume();
                  },
                  style: TextButton.styleFrom(
                    backgroundColor: DIYColors.orange_ec,
                    padding: EdgeInsets.only(
                        left: 18.w, right: 18.w, top: 8.h, bottom: 8.h),

                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    alignment: Alignment.centerLeft,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(18.r), // 设置圆角半径
                    ),
                    side: BorderSide(width: 1.w, color: DIYColors.orange_2d),
                    // 设置边框宽度和颜色
                    iconColor: Colors.white,
                  ),
                  child: Text("重新扫描",
                      style: TextStyle(
                          color: DIYColors.orange_2d, fontSize: 14.sp)))),
          SizedBox(height: _isVisible ? 10.h : 30.h),
          Expanded(
              child: Container(
                  width: double.infinity,
                  height: 300.h,
                  margin: EdgeInsets.only(left: 15.w, right: 15.w),
                  child: Expanded(
                      child: ListView.builder(
                          itemCount: _scanResults?.length ?? 0,
                          itemBuilder: (context, index) {
                            return _listTile(_scanResults[index]);
                          })))),
          SizedBox(height: 30.h),
          GestureDetector(
              onTap: () {},
              child: Text("为什么未搜索到设备？",
                  style:
                      TextStyle(color: DIYColors.orange_2d, fontSize: 16.sp))),
          SizedBox(height: _isVisible ? 15.h : 18.h),
          Container(
              margin: EdgeInsets.only(left: 30.w, right: 30.w),
              height: 50.h,
              width: double.infinity,
              child: Expanded(
                  child: TextButton(
                      onPressed: () {},
                      style: TextButton.styleFrom(
                        backgroundColor: DIYColors.orange_2d,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                        alignment: Alignment.centerLeft,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(18.r), // 设置圆角半径
                        ),
                      ),
                      child: Center(
                          child: Text("扫一扫",
                              style: TextStyle(
                                  color: Colors.white, fontSize: 14.sp)))))),
          SizedBox(height: 20.h),
        ])));
  }

  void resume() {
    _rotationController.repeat();
    _isVisible = false;
    _scanResults.clear();

    setState(() {});
    scan();
  }

  Widget _listTile(ScanResult scanResult) {
    return GestureDetector(
        onTap: () {
          ScanBluetoothUtil.instance.stopPressed();
          RouteUtils.push(
              context,
              BleConnectPage(
                device: scanResult.device,
              ));
        },
        child: Container(
            margin: EdgeInsets.only(top: 15.w),
            padding: EdgeInsets.all(15.r),
            width: double.infinity,
            height: 90.h,
            decoration: Utils.instance.decorationColor(Colors.white, 12.r),
            child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
              Image.asset(Utils.instance.getImagePathPNG("icon_scan_device")),
              Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                Text(scanResult.device.platformName,
                    style: TextStyle(color: Colors.black, fontSize: 16.sp)),
                SizedBox(height: 10.h),
                Text(scanResult.device.remoteId.str,
                    style:
                        TextStyle(color: DIYColors.gray_99, fontSize: 14.sp)),
              ]),
              const Expanded(child: SizedBox()),
              GestureDetector(
                  onTap: () {},
                  child: Image.asset(Utils.instance.getImagePathPNG("connect"),
                      width: 24.w, height: 24.h))
            ])));
  }
}
